<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller {


    protected $user_info;
    public function __construct() {
        parent::__construct(FALSE);
        $this->load->model("user_model");
		$this->load->helper('cookie');

    }



     public function index()
	{
		$data["account"] 	= get_cookie('account');
		$data["password"] 	= get_cookie('password');
		$this->load->view('/admin/login',$data);
	}



    public function check_account() {

		if(!$this->input->post("name")){
			die("error");
		}
		$condition  	=  array("account"=>trim($this->input->post("name")));
        $result = $this->table_model->get_array_one("user",$condition);
		if(empty($result)){
			echo "ok";
		}else{
			echo "error";
		}
    }

    public function check_name() {

		if(!$this->input->post("name")){
			die("error");
		}
		$condition  	=  array(
								"name"	     =>	trim($this->input->post("name"))
								);
        $result = $this->table_model->get_array_one("department",$condition);
		if(empty($result)){
			echo "ok";
		}else{
			echo "error";
		}
    }


       public function check_phone() {

		if(!$this->input->post("phone")){
			die("error1");
		}
		$phone = $this->input->post("phone");
		$condition  	=  array(
								"tel"	     =>	trim($phone)
								);
        $result = $this->table_model->get_array_one("user",$condition);
		if(empty($result)){
			echo "ok";
		}else{
			echo "error2";
		}
    }





	public function check_login()
	{
            $account     		= $this->input->post('account');
	    	$password    		= $this->input->post('password');
	    	$remember 			= $this->input->post("remember");
	    	//$account     		= "189";
	    	//$password    		= "123456";
	    	//$remember 			= 1;

			$data["account"]	= $account;
			$data["password"]	= $password;

	        $this->user_info    = $this->user_model->get_user($account,md5($password));
	        $data["user_info"]  = $this->user_info;
			if($this->user_model->exists()) {
				$this->session->set_userdata($data);
				redirect(site_url('/admin/login/main'));
			}else{
				redirect(site_url('/'));
			}


	}
	public  function  login_log($user_id) {

		$ip			= $_SERVER["REMOTE_ADDR"];
		$data 		=  array(
						 "user_id"		=> $user_id,
						 "ip"			=> $ip,
						 "login_time"	=>time()
						);
		$uid 		=  $this->table_model->add("user_log",$data) ;
		$condition 	=  array("id"	=> $user_id);
		$user_data 	=  array("last_login_time"=>time(),);
		$uid 		=  $this->user_model->save($condition,$user_data) ;
	}

	public  function  setCookie($arr = array()) {

            $host = parse_url(base_url());
			foreach($arr as  $key=>$row){
				$cookie = array(
				    'name'   => $key,
				    'value'  => $row,
				    'expire' => '86500000',
				    'domain' => $host['host'],
				    'path'   => '/',
				    'prefix' => 'myprefix_',
				    'secure' => TRUE
				);

				set_cookie($cookie);
			}
	}
	public  function  delCookie($arr = array()) {
 			$host = parse_url(base_url());
			foreach($arr as  $key=>$row){
				$cookie = array(
				    'name'   => "",
				    'value'  => "",
				    'expire' => '',
				    'domain' => $host['host'],
				    'path'   => '/',
				    'prefix' => 'myprefix_'
				);
				delete_cookie($cookie);
			}
	}



	public  function  main() {

	    $user_info 		= $this->session->userdata("user_info");
	    if(!empty($user_info)){
		    $menu	  				= $this->get_menu_json($user_info);
		    $data["menu"]  			= str_replace("\"","'",$menu);
		  	$data["account"]    	= $user_info["account"];
			$data["login_time"]   	= date('Y-m-d H:i:s',time());
		    $this->load->view('admin/main',$data);
	    }else{
			redirect(site_url('/admin'));
	    }
	}




	public  function  get_menu_json($user_info) {

		$rules  =  explode(",",$user_info["rules"]);
		if($user_info["group_id"] ==1)  {
				$condition  		= array(
									"level <=" => 2,
									);
		}else{
			$condition  		= array(
									"level <=" => 2,
									"status"   => 1
									);
		}

        $data	    =	 $this->table_model->get_array("auth_rule",$condition,"","sort","asc");
        $arr        = array();
		foreach($data  as $row){
			$row["menu_id"] 		= $row["id"];
			$row["menuname"] 	= $row["title"];
            if($user_info["group_id"]  ==1 || $user_info["group_id"]  ==2 || in_array($row["id"],$rules) ){  //group_id ==1  超级管理员
				$row["url"] 		= site_url($row["module"]."/".$row["name"]);
				$arr[]				= $row;
			}
		}

		$tree = arr2tree($arr);
		$temp["menus"]	= $tree;
		$result 		= $temp;
		$json_str = json_encode($result);
		return   $json_str;

    }



    public  function  check_code() {

    	   	$code 		= strtolower(trim($this->input->post("code")));
    	 	$scode 		= strtolower($_SESSION['scode']);
			if($code == $scode){
				 $result 	= array(
					 					"status" 	=> 1,
					 					"scode"		=> $scode
					 					);
			}else{
				 $result 	= array(
					 					"status" 	=> 0,
					 					"scode"		=> $scode
					 					);
			}
			$json_str = json_encode($result);
			echo $json_str;
    }



  public  function  check_verify() {

    	   	if($this->input->is_ajax_request()) {  // 是否ajax提交
		    	   	$code 		= strtolower(trim($this->input->post("code")));
		    	 	$account 	= $this->input->post("account");
		    	 	$password 	= $this->input->post("password");

	  	        	$this->user_info    = $this->user_model->get_user($account,md5($password));
	  	        	$data["user_info"]  = $this->user_info;
						if($this->user_model->exists()) {
							$this->session->set_userdata($data);
							 $result 	= array(
							 					"status" 	=> 1,
							 					"info"   	=> "success",
							 					"account" 	=> $account,
							 					"password" 	=> $password,
							 					);
							$json_str = json_encode($result);
							echo $json_str;
						}else{
							 $this->error("用户名或密码错误");
						}

    	   	}else{
    	   		$this->error("非法访问！");
    	   	}
    }



   public function change_password() {
   	    $this->load->view('admin/common/header');
  		$this->load->view('admin/change_password');

   }

   public function change_password_save(){
		$this->user_info = $this->session->userdata('user_info');
        if($this->user_info["account"]) {
        	$this->account 	    = $this->user_info["account"];
   		 	$condition   = array(
	        					"account" 	=> $this->account ,
	        					"password" 	=> md5($this->input->post("oldpassword")),
	        				);
	        $result      = $this->user_model->get_user_info($condition);
   	     	if($this->user_model->exists()) {
                $condition  = array("account" 	=> $this->account);
                $data 		= array("password" 	=> md5($this->input->post("password")),);
				$result 	= $this->table_model->save("user",$condition,$data);
				$this->success("密码修改成功!");
   	     	}else{
   	     		$this->error("旧密码不正确");
   	     	}

        }else{
        	$this->error("非法访问");
        }
   }
   public function send_msg(){
			$code = rands();
			$phone = $this->input->post("phone");
			if(send_msg($phone,"register_content",$code)){
				$data =  array("register_code"=>$code);
				$this->session->set_userdata("register_code",$code);
				$this->success($code);
			}else{
				$this->error($code);
			}
	}

   public function forget_password()
	{
		$this->load->view('/admin/forget_password');
	}


  public function reset_password() {
		if($this->input->is_ajax_request()) {  // 是否ajax提交
			$this->data = $this->input->post();
			$this->data["password"] 	= md5($this->data["password"]);
	        $condition  				= array("tel" => $this->data["phone"]);
	        unset($this->data["phone"]);
	        unset($this->data["recpwd"]);
			unset($this->data["code"]);
	        $result 					= $this->table_model->save("user",$condition,$this->data) ;
	        if($result) {
	       	 $this->success("修改成功");
	        }else{
	       	 $this->error("修改失败");
	        }

		}

  }

   public function show_result()
    {
        $jsonStr = json_encode($this->result);
        echo $jsonStr;
        exit(0);
    }

   public function success($msg = "", $result = "",$status="1")
    {
        $this->result['status'] 	= $status;
        $this->result['error_code'] = "0";

        if ($msg != '') {
            $this->result['info'] = $msg;
        }

        if (is_array($result)) {
            $this->result['result'] = $result;
        }
        $this->show_result();
    }

    public function error($error, $error_code = -1,$status="0")
    {
        $this->result['status'] = $status;
        $this->result['error_code'] = $error_code;
        if (is_array($error)) {
            $this->result['info'] = strip_tags(implode($error, "\n"));
        } else {
            $this->result['info'] = strip_tags($error);
        }

        $this->show_result();
    }



	public  function verify_code(){
 		$this->load->library('Comm_class');
 		$this->comm_class->verify_code();
 	}

}